﻿// FileLoggerProvider.cs
using Microsoft.Extensions.Logging;

namespace SerialInput;

public class FileLoggerProvider : ILoggerProvider
{
    private readonly string _logPath;

    public FileLoggerProvider()
    {
        _logPath = Path.Combine(
            Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
            "ScannerService");

        Directory.CreateDirectory(_logPath);
    }

    public ILogger CreateLogger(string categoryName)
    {
        return new FileLogger(categoryName, _logPath);
    }

    public void Dispose() { }
}

public class FileLogger : ILogger
{
    private readonly string _categoryName;
    private readonly string _logPath;

    public FileLogger(string categoryName, string logPath)
    {
        _categoryName = categoryName;
        _logPath = logPath;
    }

    public IDisposable BeginScope<TState>(TState state) => null!;

    public bool IsEnabled(LogLevel logLevel) => logLevel >= LogLevel.Information;

    public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
    {
        if (!IsEnabled(logLevel)) return;

        try
        {
            string logFile = Path.Combine(_logPath, $"scanner_{DateTime.Now:yyyyMMdd}.log");
            string message = formatter(state, exception);
            string logEntry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{logLevel}] [{_categoryName}] {message}";

            if (exception != null)
            {
                logEntry += $"\r\n{exception}";
            }

            logEntry += "\r\n";

            File.AppendAllText(logFile, logEntry);
        }
        catch
        {
            // 忽略日志写入错误
        }
    }
}